package org.skydiveapphd;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.skydiveapphd.ui.FragmentHelper;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.AltitudeUnit;
import org.skydiveapplibrary.data.FreefallProfileType;
import org.skydiveapplibrary.data.LogEntry;
import org.skydiveapphd.interfaces.AircraftNotifier;
import org.skydiveapphd.interfaces.DiagramNotifier;
import org.skydiveapphd.interfaces.LocationNotifier;
import org.skydiveapphd.interfaces.NotesNotifier;
import org.skydiveapphd.interfaces.RigNotifier;
import org.skydiveapphd.interfaces.SkydiveTypeNotifier;
import org.skydiveapplibrary.repository.AircraftRepository;
import org.skydiveapplibrary.repository.LocationRepository;
import org.skydiveapplibrary.repository.LogEntryRepository;
import org.skydiveapplibrary.repository.RigRepository;
import org.skydiveapplibrary.repository.SkydiveTypeRepository;
import org.skydiveapplibrary.ui.FormatUtility;
import org.skydiveapplibrary.ui.NumberDialog;
import org.skydiveapplibrary.ui.NumberDialog.OnNumberSetListener;
import org.skydiveapplibrary.util.FreefallTimeCalculator;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;

public class LogEntryEditActivity extends Fragment implements NotesNotifier, AircraftNotifier, LocationNotifier, RigNotifier, SkydiveTypeNotifier, DiagramNotifier
{
	
	// repositories
	private LogEntryRepository repository;
	private LocationRepository locRepository;
	private AircraftRepository aircraftRepository;
	private RigRepository rigRepository;
	private SkydiveTypeRepository skydiveTypeRepository;
	
	// data
	private boolean isEdit = false;
	private boolean isCopy = false;
	private boolean isUpdated = false;
	private LogEntry logEntry;
	
	
	// listeners
	private OnClickListener saveListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			save();
		}
	};
	private OnClickListener deleteListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showDeleteWarning();
		}
	};
	private OnClickListener cancelListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			if (isUpdated == false && isEdit == true)
			{
				isUpdated = checkForChanges();
			}
			
			if (isUpdated == true || isEdit == false)
			{
				showSaveWarning();
			} else 
			{
				closeWithoutSaving();
			}
		}
	};
	private DialogInterface.OnClickListener deleteConfirmListener = new DialogInterface.OnClickListener()
	{
		@Override
		public void onClick(DialogInterface arg0, int arg1)
		{
			delete();
		}
	};
	private OnClickListener estimateFFTimeListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			estimateFreefallTime();
		}
	};
	private OnClickListener notesEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			isUpdated = (isUpdated || checkForChanges() ? true : false);
	    	// Create new fragment and transaction

			Bundle args = new Bundle();
			args.putString(Constants.EXTRA_FRAG_TAG, LogEntryEditActivity.this.getTag());
			args.putString(Constants.EXTRA_NOTES, logEntry.getNotes());
						
			FragmentHelper.getInstance().openFragment(NotesEditActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_NOTES_EDIT, getFragmentManager());
		}
	};
	private OnClickListener locationEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{	
			isUpdated = (isUpdated || checkForChanges() ? true : false);
			
			Bundle args = new Bundle();
			args.putString(Constants.EXTRA_FRAG_TAG, LogEntryEditActivity.this.getTag());
			
			if (logEntry.getLocation() != null)
			{
				args.putInt(Constants.EXTRA_LOCATION_ID, logEntry.getLocation().getId());
			}
			
			FragmentHelper.getInstance().openFragment(LocationSelectListActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_LOCATION_SELECT_LIST, getFragmentManager());
		}
	};
	private OnClickListener jumpNumberEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showJumpNumberDialog();
		}
	};
	private OnNumberSetListener jumpNumberSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateJumpNumber(number);
			isUpdated = true;
		}
	};
	private OnClickListener dateEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showDateDialog();
		}
	};
	private OnDateSetListener dateSetListener = new OnDateSetListener()
	{
		@Override
		public void onDateSet(DatePicker dialog, int year, int month, int day)
		{
			Calendar cal = Calendar.getInstance();
			cal.set(year, month, day);
			updateDate(cal.getTime());
			isUpdated = true;
		}
	};
	private OnClickListener aircraftEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			isUpdated = (isUpdated || checkForChanges() ? true : false);
			
			Bundle args = new Bundle();
			args.putString(Constants.EXTRA_FRAG_TAG, LogEntryEditActivity.this.getTag());
			
			if (logEntry.getAircraft() != null)
			{
				args.putInt(Constants.EXTRA_AIRCRAFT_ID, logEntry.getAircraft().getId());
			}

			FragmentHelper.getInstance().openFragment(AircraftSelectListActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_AIRCRAFT_SELECT_LIST, getFragmentManager());
		}
	};
	private OnClickListener gearEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			isUpdated = (isUpdated || checkForChanges() ? true : false);
			
			Bundle args = new Bundle();
			args.putString(Constants.EXTRA_FRAG_TAG, LogEntryEditActivity.this.getTag());
			args.putSerializable(Constants.EXTRA_SELECTED_RIG_IDS, (Serializable) getSelectedRigIds());
			
			FragmentHelper.getInstance().openFragment(GearListSelectActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_GEAR_SELECT_LIST, getFragmentManager());
		}
	};
	private OnClickListener skydiveTypeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			isUpdated = (isUpdated || checkForChanges() ? true : false);
			
			Bundle args = new Bundle();
			args.putString(Constants.EXTRA_FRAG_TAG, LogEntryEditActivity.this.getTag());
			
			if (logEntry.getSkydiveType() != null)
			{
				args.putInt(Constants.EXTRA_SKYDIVE_TYPE_ID, logEntry.getSkydiveType().getId());
			}
		
			FragmentHelper.getInstance().openFragment(SkydiveTypeSelectListActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_SKYDIVE_TYPE_SELECT_LIST, getFragmentManager());
		}
	};
	private OnClickListener diagramEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			isUpdated = (isUpdated || checkForChanges() ? true : false);
			
			Bundle args = new Bundle();
			args.putString(Constants.EXTRA_FRAG_TAG, LogEntryEditActivity.this.getTag());
			args.putByteArray(Constants.EXTRA_DIAGRAM, logEntry.getDiagram());
			
			FragmentHelper.getInstance().openFragment(LogEntryDiagramActivity.newInstance(args), R.id.wholePage, 
					Constants.TAG_LOG_ENTRY_DIAGRAM, getFragmentManager());
		}
	};
	
	
	public static LogEntryEditActivity newInstance(Bundle args) 
	{
		LogEntryEditActivity f = new LogEntryEditActivity();
		f.setArguments(args);
		return f;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setHasOptionsMenu(true);
		
		repository = new LogEntryRepository(getActivity());
		locRepository = new LocationRepository(getActivity());
		aircraftRepository = new AircraftRepository(getActivity());
		rigRepository = new RigRepository(getActivity());
		skydiveTypeRepository = new SkydiveTypeRepository(getActivity());

		// set isEdit and isCopy flag
		isEdit = (getArguments().containsKey(Constants.EXTRA_LOG_ENTRY_ID));
		isCopy = (getArguments().containsKey(Constants.EXTRA_LOG_ENTRY_COPY));
		
		// load data
		loadData();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{	
	    // Inflate the layout for this fragment
	    return inflater.inflate(R.layout.log_entry_edit_view, container, false);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		// init ui
		initializeUI();
		
		// update fields
		updateFields();
	}
	
	
	private void loadData()
	{
		// determine add vs. edit
		if (isEdit)
		{
			// editing
			int logEntryId = getArguments().getInt(Constants.EXTRA_LOG_ENTRY_ID, 0);
			logEntry = repository.getLogEntry(logEntryId);
		}
		else if (isCopy)
		{
			// create new using last logs fields
			logEntry = repository.getNewFromLastEntry();
		}
		else
		{
			// adding
			logEntry = new LogEntry();
			// set defaults
			repository.setDefaults(logEntry);
		}
	}
	
	private void initializeUI()
	{
	
		// set header text
		TextView headerTextView = (TextView) getActivity().findViewById(R.id.EditHeaderTextView);
		headerTextView.setText(isEdit ?
				R.string.log_entry_edit_label : R.string.log_entry_new_label);
		
		// set jump number listener
		TextView jumpNumberField = (TextView) getActivity().findViewById(R.id.LogEntryJumpNumberField);
		jumpNumberField.setOnClickListener(jumpNumberEditListener);
		
		// set date listener
		TextView dateField = (TextView) getActivity().findViewById(R.id.LogEntryDateField);
		dateField.setOnClickListener(dateEditListener);

		// set location listener
		TextView locField = (TextView) getActivity().findViewById(R.id.LogEntryLocationField);
		locField.setOnClickListener(locationEditListener);
		
		// set aircraft listener
		TextView airField = (TextView) getActivity().findViewById(R.id.LogEntryAircraftField);
		airField.setOnClickListener(aircraftEditListener);

		// set gear listener
		TextView gearField = (TextView) getActivity().findViewById(R.id.LogEntryGearField);
		gearField.setOnClickListener(gearEditListener);
		
		// set type listener
		TextView typeField = (TextView) getActivity().findViewById(R.id.LogEntryTypeField);
		typeField.setOnClickListener(skydiveTypeEditListener);
		
		// set exit altitude label
		TextView eaLabel = (TextView) getActivity().findViewById(R.id.LogEntryExitAltitudeLabel);
		eaLabel.setText(MessageFormat.format(
				getString(R.string.log_entry_exit_altitude_label_format),
				getString(logEntry.getAltitudeUnit().getResourceId())));
			
		// set deply altitude label
		TextView daLabel = (TextView) getActivity().findViewById(R.id.LogEntryDeploymentAltitudeLabel);
		daLabel.setText(MessageFormat.format(
				getString(R.string.log_entry_deployment_altitude_label_format),
				getString(logEntry.getAltitudeUnit().getResourceId())));
			
		// set diagram listener
		TableRow diRow = (TableRow) getActivity().findViewById(R.id.LogEntryDiagramRow);
		diRow.setOnClickListener(diagramEditListener);
				
		// set notes listener
		TextView nField = (TextView) getActivity().findViewById(R.id.LogEntryNotesField);
		nField.setOnClickListener(notesEditListener);
		
		// add button click listeners
		ImageButton saveButton = (ImageButton) getActivity().findViewById(R.id.LogEntrySaveButton);
		saveButton.setOnClickListener(saveListener);
		
		ImageButton cancelButton = (ImageButton) getActivity().findViewById(R.id.LogEntryCancelButton);
		cancelButton.setOnClickListener(cancelListener);
		
		ImageButton deleteButton = (ImageButton) getActivity().findViewById(R.id.LogEntryDeleteButton);
		deleteButton.setOnClickListener(deleteListener);
		
		View estimateFFTimeButton = getActivity().findViewById(R.id.LogEntryEstimateFreefallTimeButton);
		estimateFFTimeButton.setOnClickListener(estimateFFTimeListener);
		
		// show/hide delete button
		deleteButton.setVisibility(isEdit ? View.VISIBLE : View.GONE);
	}

	private void updateFields()
	{
		
		// set jump number
		TextView jumpNumberField = (TextView) getActivity().findViewById(R.id.LogEntryJumpNumberField);
		jumpNumberField.setText(FormatUtility.toNumericString(logEntry.getJumpNumber()));
		
		// set date
		TextView dateField = (TextView) getActivity().findViewById(R.id.LogEntryDateField);
		dateField.setText(FormatUtility.toDateString(getActivity(), logEntry.getDate()));
		
		// set type
		TextView typeField = (TextView) getActivity().findViewById(R.id.LogEntryTypeField);
		typeField.setText(logEntry.getSkydiveType() == null ? "" :
			logEntry.getSkydiveType().getName());
		
		// set location
		TextView locField = (TextView) getActivity().findViewById(R.id.LogEntryLocationField);
		locField.setText(logEntry.getLocation() == null ? "" :
			logEntry.getLocation().getName());
		
		// set aircraft
		TextView airField = (TextView) getActivity().findViewById(R.id.LogEntryAircraftField);
		airField.setText(logEntry.getAircraft() == null ? "" :
			logEntry.getAircraft().getName());
		
		// set gear
		TextView gearField = (TextView) getActivity().findViewById(R.id.LogEntryGearField);
		gearField.setText(getGearText());
		
		// init exit altitude
		if (logEntry.getExitAltitude() != null)
		{
			EditText eaField = (EditText) getActivity().findViewById(R.id.LogEntryExitAltitudeField);
			eaField.setText(FormatUtility.toNumericString(logEntry.getExitAltitude()));
		}
		
		// init deployment altitude
		if (logEntry.getDeploymentAltitude() != null)
		{
			EditText daField = (EditText) getActivity().findViewById(R.id.LogEntryDeploymentAltitudeField);
			daField.setText(FormatUtility.toNumericString(logEntry.getDeploymentAltitude()));
		}
		
		// set freefall time
		if (logEntry.getFreeFallTimeSeconds() != null)
		{
			EditText ffField = (EditText) getActivity().findViewById(R.id.LogEntryFreefallTimeField);
			ffField.setText(FormatUtility.toNumericString(logEntry.getFreeFallTimeSeconds()));
		}
		
		// set cutaway
		CheckBox caField = (CheckBox) getActivity().findViewById(R.id.LogEntryCutawayField);
		caField.setChecked(logEntry.isCutaway());
		
		// set diagram
		ImageView diField = (ImageView) getActivity().findViewById(R.id.LogEntryDiagramField);
		if (logEntry.getDiagram() != null)
		{
			Bitmap bitmap = BitmapFactory.decodeByteArray(logEntry.getDiagram(), 0, logEntry.getDiagram().length);
			diField.setImageBitmap(bitmap);
		}
		
		// set notes
		TextView nField = (TextView) getActivity().findViewById(R.id.LogEntryNotesField);
		nField.setText(logEntry.getNotes());
		
		// set signature
		View signatureGroup =  getActivity().findViewById(R.id.LogEntrySignatureGroup);
		if (logEntry.getSignature() == null)
		{
			signatureGroup.setVisibility(View.GONE);
			}
		else
		{
			signatureGroup.setVisibility(View.VISIBLE);
			// set signature image
			Bitmap bitmap = BitmapFactory.decodeByteArray(logEntry.getSignature().getImage(), 0, logEntry.getSignature().getImage().length);
			ImageView signatureField = (ImageView) getActivity().findViewById(R.id.LogEntrySignatureField);
			signatureField.setImageBitmap(bitmap);
			// set license
			TextView licenseField = (TextView) getActivity().findViewById(R.id.LogEntryLicenseField);
			licenseField.setText(logEntry.getSignature().getLicense());
		}
	}

	private void estimateFreefallTime()
	{
		// get fields
		EditText exitAltField = (EditText) getActivity().findViewById(R.id.LogEntryExitAltitudeField);
		EditText deplAltField = (EditText) getActivity().findViewById(R.id.LogEntryDeploymentAltitudeField);
		
		// get values
		FreefallProfileType freefallProfile =
			(logEntry.getSkydiveType() != null && logEntry.getSkydiveType().getFreefallProfileType() != null) ?
					logEntry.getSkydiveType().getFreefallProfileType() : FreefallProfileType.Horizontal;
		AltitudeUnit altUnit = logEntry.getAltitudeUnit();
		int exitAlt = FormatUtility.fromNumericString(exitAltField.getText().toString());
		int deplAlt = FormatUtility.fromNumericString(deplAltField.getText().toString());
		
		// get estimate
		int estimate = FreefallTimeCalculator.calculateFreefallTime(
				freefallProfile, exitAlt, deplAlt, altUnit);
		
		// update ui
		TextView ffTimeField = (TextView) getActivity().findViewById(R.id.LogEntryFreefallTimeField);
		ffTimeField.setText(String.valueOf(estimate));
	}
	
	private String getGearText()
	{
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < logEntry.getRigs().size(); i++)
		{
			builder.append(logEntry.getRigs().get(i).getName());
			if (i < logEntry.getRigs().size() - 1)
			{
				builder.append(", ");
			}
		}
		return builder.toString();
	}
	
	private void showJumpNumberDialog()
	{
		// init dialog
		NumberDialog dialog = new NumberDialog(
				getActivity(),
				R.string.jump_number_title,
				logEntry.getJumpNumber(),
				jumpNumberSetListener);
		// show dialog
		dialog.show();
	}

	private List<Integer> getSelectedRigIds()
	{
		List<Integer> ids = new ArrayList<Integer>();
		for (int i = 0; i < logEntry.getRigs().size(); i++)
		{
			ids.add(logEntry.getRigs().get(i).getId());
		}
		return ids;
	}
	
	private void save()
	{
		checkForChanges();
		
		// save
		if (isEdit)
		{
			repository.updateLogEntry(logEntry);
		}
		else
		{
			repository.addLogEntry(logEntry);
		}
		
		// finish		

		// update logEntryListActivity
		((LogEntryListActivity) getFragmentManager().findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST)).updateListView();
		
		// update stats tab
		((MainActivity) getActivity()).updateStatsTab();
		
		getFragmentManager().popBackStack();
		FragmentHelper.getInstance().notifyOfClose(this.getFragmentManager());
	}
	
	private void delete()
	{
		// delete log entry
		repository.deleteLogEntry(logEntry);
		
		// update stats tab
		((MainActivity) getActivity()).updateStatsTab();
		
		// finish
		closeWithoutSaving();
	}
	
	private void closeWithoutSaving()
	{
		// update logEntryListActivity
		((LogEntryListActivity) getFragmentManager().findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST)).updateListView();
		
		getFragmentManager().popBackStack();
		FragmentHelper.getInstance().notifyOfClose(this.getFragmentManager());
	}
	
	private boolean checkForChanges()
	{
		boolean returnValue = false;
		
		// check exit altitude
		EditText eaField = (EditText) getActivity().findViewById(R.id.LogEntryExitAltitudeField);
		String eaString = eaField.getText().toString();
		
		if (logEntry.getExitAltitude() != FormatUtility.fromNumericString(eaString))
		{
			returnValue = true;

			// set exit altitude
			logEntry.setExitAltitude(FormatUtility.fromNumericString(eaString));
		}

		
		// check deployment altitude
		EditText daField = (EditText) getActivity().findViewById(R.id.LogEntryDeploymentAltitudeField);
		String daString = daField.getText().toString();

		if (logEntry.getDeploymentAltitude() != FormatUtility.fromNumericString(daString))
		{
			returnValue = true;
			
			// set deployment altitude
			logEntry.setDeploymentAltitude(FormatUtility.fromNumericString(daString));
		}
		
		// check freefall time
		EditText ffField = (EditText) getActivity().findViewById(R.id.LogEntryFreefallTimeField);
		String ffString = ffField.getText().toString();

		if (logEntry.getFreeFallTimeSeconds() != FormatUtility.fromNumericString(ffString))
		{
			returnValue = true;
			
			// set freefall time
			logEntry.setFreeFallTimeSeconds(FormatUtility.fromNumericString(ffString));
		}
		
		// check cutaway
		CheckBox caField = (CheckBox) getActivity().findViewById(R.id.LogEntryCutawayField);
		
		if (logEntry.isCutaway() != caField.isChecked())
		{
			returnValue =  true;
			
			// set cutaway
			logEntry.setCutaway(caField.isChecked());
		}
		
		return returnValue;
	}
	
	private void showSaveWarning()
	{
		// create alert dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(R.string.log_entry_save_warning);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.save_confirmation);
		builder.setPositiveButton(R.string.yes_button, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				save();
	           }       
		});
		builder.setNeutralButton(R.string.no_button, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// finish
				closeWithoutSaving();
	           }       
		});
		builder.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				//clear and queued transactions
				FragmentHelper.getInstance().cancelRequest();
			}
		});
			
		AlertDialog dialog = builder.create();
		// show dialog
		dialog.show();
	}

	private void updateJumpNumber(int jumpNumber)
	{
		// update log entry
		logEntry.setJumpNumber(jumpNumber);
		
		// update ui
		TextView jnField = (TextView) getActivity().findViewById(R.id.LogEntryJumpNumberField);
		jnField.setText(FormatUtility.toNumericString(logEntry.getJumpNumber()));
	}
	
	private void showDeleteWarning()
	{
		// create alert dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(R.string.log_entry_delete_warning);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.delete_confirmation);
		builder.setPositiveButton(R.string.yes_button, deleteConfirmListener);
		builder.setNegativeButton(R.string.no_button, null);
		AlertDialog dialog = builder.create();
		// show dialog
		dialog.show();
	}
	
	private void showDateDialog()
	{
		// create date dialog
		Calendar cal = Calendar.getInstance();
		cal.setTime(logEntry.getDate());
		DatePickerDialog dialog = new DatePickerDialog(
				getActivity(),
				dateSetListener,
				cal.get(Calendar.YEAR),
				cal.get(Calendar.MONTH),
				cal.get(Calendar.DAY_OF_MONTH));
		// show dialog
		dialog.show();
	}
	
	private void updateDate(Date date) 
	{
		// update log entry
		logEntry.setDate(date);
		
		// update ui
		TextView dateField = (TextView) getActivity().findViewById(R.id.LogEntryDateField);
		dateField.setText(FormatUtility.toDateString(getActivity(), logEntry.getDate()));
	}

	public void updateLocation(int locationID)
	{
		// update log entry
		isUpdated = true;
		logEntry.setLocation(locRepository.getLocation(locationID));
	}
	
	public void updateNotes(String notes)
	{
		// update log entry
		isUpdated = true;
		logEntry.setNotes(notes);
	}

	public void updateAircraft(int aircraftId)
	{
		// update log entry
		isUpdated = true;
		logEntry.setAircraft(aircraftRepository.getAircraft(aircraftId));
	}

	public void updateRig(List<Integer> ids)
	{
		// update log entry
		isUpdated = true;
		logEntry.getRigs().clear();
		logEntry.getRigs().addAll(rigRepository.getRigs(ids));
	}
	
	public void updateSkydiveType(int id)
	{
		// update log entry
		isUpdated = true;
		logEntry.setSkydiveType(skydiveTypeRepository.getSkydiveType(id));
	}
	
	public void updateDiagram(byte[] data)
	{
		// update log entry
		isUpdated = true;
		logEntry.setDiagram(data);
		
		try
		{
			// get bitmap
			Bitmap bitmap = null; 
			if (logEntry.getDiagram() != null)
			{
				bitmap = BitmapFactory.decodeByteArray(logEntry.getDiagram(), 0, logEntry.getDiagram().length);
			}
			
			// update UI
			ImageView diField = (ImageView) getActivity().findViewById(R.id.LogEntryDiagramField);
			diField.setImageBitmap(bitmap);
		}
		catch (Exception ex)
		{
			// error
			Log.e(LogEntryEditActivity.class.getName(), ex.getMessage());
		}
	}
	
	public boolean requestClose()
	{
		if (isUpdated == false && isEdit == true)
		{
			isUpdated = checkForChanges();
		}

		if (isUpdated == true || isEdit == false)
		{
			showSaveWarning();
			return true;
		}
		else
		{
			closeWithoutSaving();
			return false;
		}
	}
}